package P1线性结构;

public class InfixToSuffix {
    public static void main(String[] args) {
        String expression = "(10+20/2*3)/2+8";
        expression = infixToSuffix(expression);
        System.out.println(expression);
    }

    private static String infixToSuffix(String expression) {
        LinkedList<String> suffixList = new LinkedList<>();
        LinkedList<String> opStack = new LinkedList<>();
        expression = format(expression);
        String[] tokens = expression.split(" ");
        for (String token : tokens) {
            if (token.length() != 0) {
                if (token.equals("+") || token.equals("-")) {
                    while (!opStack.isEmpty() && !opStack.peek().equals("(")) {
                        suffixList.add(opStack.pop());
                    }
                    opStack.push(token);
                } else if (token.equals("*") || token.equals("/")) {
                    while (!opStack.isEmpty() && (opStack.peek().equals("*") || opStack.peek().equals("/"))) {
                        suffixList.add(opStack.pop());
                    }
                    opStack.push(token);
                } else if (token.equals("(")) {
                    opStack.push("(");
                } else if (token.equals(")")) {
                    while (!opStack.peek().equals("(")) {
                        suffixList.add(opStack.pop());
                    }
                    opStack.pop();
                } else {
                    suffixList.add(token);
                }
            }
        }
        while (!opStack.isEmpty()) {
            suffixList.add(opStack.pop());
        }
        StringBuilder sb = new StringBuilder();
        for (String token : suffixList) {
            sb.append(token);
            sb.append(' ');
        }
        return sb.toString();
    }

    private static String format(String expression) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')') {
                sb.append(' ');
                sb.append(c);
                sb.append(' ');
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}